#include <nice2d/draggableentity.h>
#include <nice2d/application.h>

IMPLEMENT_OBJECT(DraggableEntity,Entity)

class DraggableEntityData
{
public:
    bool dragable = true;
    bool resizeable = true;
    sf::Vector2i oldMousePosition;
    EntityWeakPointer target;
};

DraggableEntity::DraggableEntity(const sf::Vector2f &size):
    Entity(size),
    data(new DraggableEntityData())
{
}

DraggableEntity::~DraggableEntity()
{
}

void DraggableEntity::setDragable(bool dragable)
{
    if(data->dragable != dragable)
    {
        data->dragable = dragable;
        dragableChanged(dragable);
    }
}

bool DraggableEntity::isDragable()
{
    return data->dragable;
}

void DraggableEntity::setResizeable(bool resizeable)
{
    if(data->resizeable != resizeable)
    {
        data->resizeable = resizeable;
        resizeableChanged(resizeable);
    }
}

bool DraggableEntity::isResizeable() const
{
    return data->resizeable;
}

void DraggableEntity::setTarget(EntityPointer target)
{
    data->target = target;
}

void DraggableEntity::onMousePressed(sf::Mouse::Button button)
{
    auto position = Application::getInstance()->getMousePosition();
    data->oldMousePosition.x = position.x;
    data->oldMousePosition.y = position.y;
}

void DraggableEntity::onMouseMoved(int x, int y)
{
    if(isDragable() && sf::Mouse::isButtonPressed(sf::Mouse::Left))
    {
        EntityPointer target;
        if(!data->target.expired())
            target = data->target.lock();
        else
            target = std::dynamic_pointer_cast<Entity>(shared_from_this());

        target->move(x-data->oldMousePosition.x,y-data->oldMousePosition.y);
        data->oldMousePosition = sf::Vector2i(x,y);
    }
}
